<template>
  <el-container>
    <el-header>
      <h1>发表新文章</h1>
    </el-header>
    <el-form label-position="top" :model="form" class="form-container">
      <el-form-item label="标题">
        <el-input v-model="form.title" placeholder="文章标题"></el-input>
      </el-form-item>
      <el-form-item label="短链接">
        <el-input v-model="form.slug" placeholder="文章短链接"></el-input>
      </el-form-item>
      <el-form-item label="摘要">
        <el-input
          v-model="form.description"
          placeholder="文章大致内容"
        ></el-input>
      </el-form-item>
      <el-form-item label="正文">
        <el-input
          type="textarea"
          :rows="8"
          v-model="form.body"
          placeholder="输入文字正文"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          size="large"
          class="publish-button"
          @click="createArticle"
          >发布</el-button
        >
      </el-form-item>
    </el-form>
  </el-container>
</template>

<script setup>
import axios from "axios"; // 引入 axios
import { ref } from "vue";
import { ElMessage } from "element-plus"; // 假设使用Element Plus版本

const form = ref({
  slug: "",
  title: "",
  description: "",
  body: "",
});

function createArticle() {
  // 从 localStorage 获取令牌
  const token = localStorage.getItem("user-token");

  if (!token) {
    alert("您还没有登录，请先登录！");
    return;
  }

  // 发送带有令牌的 POST 请求
  axios
    .post(
      "/api/articles",
      {
        slug: form.value.slug,
        title: form.value.title,
        description: form.value.description,
        body: form.value.body,
      },
      {
        headers: {
          Authorization: token,
        },
      }
    )
    .then((response) => {
      ElMessage.success("文章创建成功！");

      console.log("文章创建成功:", response.data);
      // 清空表单
      form.value.slug = "";
      form.value.title = "";
      form.value.description = "";
      form.value.body = "";
    })
    .catch((error) => {
      console.error("文章创建失败:", error);
    });
}
</script>

<style scoped>
/* 设置el-header样式 */
.el-header {
  background-color: white; /* 设置背景颜色 */
  color: #1d1c1c; /* 设置文字颜色 */
  height: 200px; /* 设置一个明确的高度，可以根据需要调整 */
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  font-size: 20px; /* 设置字体大小 */
}

.form-container {
  width: 100%;
  max-width: 960px;
  margin: 0 auto;
}

.publish-button {
  float: right;
}
</style>